package com.zackratos.androidcomponent

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.SparseArray
import androidx.core.util.set
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.zackratos.androidcomponent.databinding.ActivityMainBinding
import com.zackratos.component1.Component1Fragment
import com.zackratos.component2.Component2Fragment
import com.zackratos.component3.Component3Fragment
import com.zackratos.component4.Component4Fragment

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.viewPager2.adapter = PagerAdapter(this)
        binding.viewPager2.offscreenPageLimit = 4

        TabLayoutMediator(binding.tabLayout, binding.viewPager2,
            TabLayoutMediator.TabConfigurationStrategy { tab, position ->
                tab.text = "cpnt ${position + 1}"
            }).attach()
    }

    private class PagerAdapter(activity: FragmentActivity): FragmentStateAdapter(activity) {

        private val fragments: SparseArray<Fragment> by lazy { SparseArray<Fragment>() }

        override fun getItemCount(): Int = 4

        override fun createFragment(position: Int): Fragment {
            var fragment = fragments[position]
            if (fragment != null) {
                return fragment
            }
            fragment = when (position) {
                0 -> Component1Fragment.newInstance()
                1 -> Component2Fragment.newInstance()
                2 -> Component3Fragment.newInstance()
                3 -> Component4Fragment.newInstance()
                else -> Fragment()
            }
            fragments[position] = fragment
            return fragment
        }
    }
}
